package wangwenjun.phase1.reference.phantom;

import java.net.Socket;

/**
 * @author ChangLiang
 * @date 2020/6/17
 */
public class ClientHandlerV2 implements Runnable {

    private final Socket socket;

    public ClientHandlerV2(final Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // do chat
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // release java socket and OS socket
            this.release();
        }
    }

    private void release() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (Throwable e) {
            /**
             * 我们可以借助PhantomReference的特性，在垃圾回收器对socket对象进行回收的时候再次尝试一次清理，
             * 虽然也不能百分之百地保证资源能够彻底释放，但是这样做能够提高资源释放的概率
             */
            if (socket != null) {
                SocketCleaningTracker.track(socket);
            }
        }
    }
}
